<template>
    <div class="create-dashboard-container">
        <!-- 表单区域 -->
        <div class="dashboard-form-section">
            <div class="form-header">
                <div class="form-group">
                    <label>Topic：</label>
                    <el-input
                        v-model="dashboardForm.name"
                        placeholder="please enter the topic of your dashboard" />

                </div>

                <el-input
                    v-model="dashboardForm.description"
                    type="textarea"
                    rows="4"
                    placeholder="Please enter a description of this dashboard" />

                <div class="form-actions">

                    <el-button class="cancel-btn" @click="cancelCreate">cancel</el-button>

                    <el-button class="save-btn" type="primary" @click="saveDashboard" :loading="saving">save</el-button>

                </div>

            </div>



            <!-- 图表区域 - 使用el-row和el-col布局 -->

            <div class="charts-container">

                <el-row :gutter="20">

                    <!-- 已添加图表 -->

                    <el-col

                        v-for="(chart, index) in dashboardForm.charts"

                        :key="index"

                        :span="12">

                        <div class="chart-card">

                            <div class="chart-title">

                                <span>{{ chart.title }}</span>

                                <el-button

                                    type="danger"

                                    size="small"

                                    @click="removeChartAt(index)"

                                    :icon="Delete"

                                    circle

                                    class="delete-chart-btn"></el-button>

                            </div>

                            <!-- 图表容器 - 使用ref数组保存DOM引用 -->

                            <div

                                :ref="el => { if (el) chartRefs[index] = el }"

                                class="chart-container"

                                :id="`chart-${index}`"></div>

                        </div>

                    </el-col>



                    <!-- 添加图表按钮 - 始终显示在最后 -->

                    <el-col :span="12">

                        <div class="chart-add-card" @click="showAddChartDialog">

                            <div class="chart-add-placeholder">

                                <el-icon class="add-icon">
                                    <Plus />
                                </el-icon>

                                <div>添加图表</div>

                            </div>

                        </div>

                    </el-col>

                </el-row>

            </div>

        </div>



        <!-- 添加图表对话框 -->

        <el-dialog

            v-model="chartDialogVisible"

            :show-close="false"

            width="600px"

            custom-class="chart-dialog">

            <div class="chart-dialog-content">

                <el-select

                    v-model="chartForm.dataSource"

                    placeholder="Please select the data to be displayed"

                    class="chart-select">

                    <el-option

                        v-for="option in chartOptions.dataSources"

                        :key="option.value"

                        :label="option.label"

                        :value="option.value">

                    </el-option>

                </el-select>



                <el-select

                    v-model="chartForm.type"

                    placeholder="Please select the chart type"

                    class="chart-select"

                    :disabled="!chartForm.dataSource">

                    <el-option

                        v-for="option in availableChartTypes"

                        :key="option.value"

                        :label="option.label"

                        :value="option.value">

                        <el-icon class="option-icon">

                            <component :is="option.icon" />

                        </el-icon>

                        {{ option.label }}

                    </el-option>

                </el-select>

            </div>



            <!-- 对话框底部按钮 -->

            <template #footer>

                <div class="dialog-footer">

                    <el-button @click="chartDialogVisible = false" class="delete-btn">Cancel</el-button>

                    <el-button type="primary" @click="addChart" class="confirm-btn">Confirm</el-button>

                </div>

            </template>

        </el-dialog>

    </div>

</template>



<script setup>

import { ref, reactive, onMounted, nextTick, watch, computed, onUnmounted } from 'vue'

import { useRouter } from 'vue-router'

import { Plus, Delete } from '@element-plus/icons-vue'

import { ElMessage, ElMessageBox } from 'element-plus'

import { createDashboard, getChartOptions } from '@/api/dashboard-manage'

import * as echarts from 'echarts'



// 导入分析API

import {

    getAnalysisData,

    getProductAnalysis,

    getCustomerAnalysis,

    getShopAnalysis,

    getIncomeAnalysis
} from '@/api/analysis'



const router = useRouter()

const saving = ref(false)

const chartDialogVisible = ref(false)

const chartRefs = ref([]) // 用于存储图表DOM引用



// 仪表板表单数据

const dashboardForm = reactive({

    name: '',

    type: '',

    icon: 'DataLine',

    description: '',

    ownerId: JSON.parse(localStorage.getItem('userInfo') || '{}').id,

    charts: []

})



// 图表表单数据

const chartForm = reactive({

    title: '',

    type: '',

    dataSource: '',

    options: '',

    displayOrder: 0

})



// 图表选项数据

const chartOptions = ref({

    dataSources: [],

    chartTypes: []

})



// 获取图表选项

onMounted(async () => {

    try {

        const res = await getChartOptions()
        chartOptions.value = res



        // 如果有已添加的图表，渲染它们

        if (dashboardForm.charts.length > 0) {

            loadAllCharts()

        }

    } catch (error) {

        ElMessage.error('Failed to get chart options')

    }

})



// 根据选中的数据源过滤可用的图表类型

const availableChartTypes = computed(() => {

    if (!chartForm.dataSource) return []



    const dataSource = chartOptions.value.dataSources.find(

        ds => ds.value === chartForm.dataSource

    )



    if (!dataSource || !dataSource.supportedChartTypes) return []



    return chartOptions.value.chartTypes.filter(

        ct => dataSource.supportedChartTypes.includes(ct.value)

    )

})



// 加载图表数据并渲染

const loadChartData = async (index) => {

    const chart = dashboardForm.charts[index]

    if (!chart) return



    try {

        // 解析数据源配置

        const dataSourceConfig = JSON.parse(chart.dataSource)

        const dataSourceType = dataSourceConfig.type



        // 准备查询参数（可以从过滤条件中提取或使用默认值）

        let queryParams = {

            startDate: '2023-01-01',

            endDate: '2023-12-31'

            // 可以添加其他参数

        }



        let responseData



        // 根据数据源类型调用不同的API

        switch (dataSourceType) {
            // 核心分析数据
            case 'totalSalesProfit':
            case 'orderCount':
            case 'salesVolume':
            case 'customerCount':
                responseData = await getAnalysisData('core', queryParams)
                break



            // 产品分析数据
            case 'productCategorySales':
            case 'productUnitPriceProfit':
            case 'productCategorySalesVolume':
            case 'productCategorySalesDate':
                queryParams.category = 'Accessories'
                responseData = await getProductAnalysis(queryParams)
                break

            case 'productCategoryDistribution':
                queryParams.category = null
                responseData = await getProductAnalysis(queryParams)
                break




            // 客户分析数据
            case 'consumptionPerCapita':
            case 'customerTimePreference':
            case 'customerCityDistribution':
            case 'ageDistribution':
                queryParams.category = null
                responseData = await getCustomerAnalysis(queryParams)

                break

            // 商店分析数据
            case 'shopSalesProfit':
                queryParams.category = null
                queryParams.shopId = 21
                responseData = await getShopAnalysis(queryParams)
                break
            case 'shopDistribution':
                const obj = {
                    "startDate": null,
                    "endDate": null,
                    "category": null,
                    "city": null,
                    "shopId": null,
                    "operator": null,
                    "amount": null
                }
                responseData = await getShopAnalysis(obj)
                break

            case 'cumulativeSalesProfit':
            case 'monthlySalesProfit':
                responseData = await getIncomeAnalysis(queryParams)
                break

            default:

                throw new Error('No supported data source type')

        }



        // 提取图表所需的数据

        const chartData = extractChartData(responseData, dataSourceType, chart.type)



        // 渲染图表

        renderChart(index, chartData)

    } catch (error) {
        ElMessage.error('Failed to load chart data, using sample data for preview')

        // 加载失败时使用默认示例数据

        renderChartWithDemoData(index)

    }

}



// 从API响应中提取图表数据的辅助函数

const extractChartData = (responseData, dataSourceType, chartType) => {
    switch (dataSourceType) {
        case 'totalSalesProfit':
            return {
                color: ['#409EFF', '#67C23A'],
                legend: {
                    data: ['Total Sales', 'Profit'],
                },
                xAxis: responseData.chartData.months,
                series: [
                    {
                        name: 'Total Sales',
                        type: chartType,
                        data: responseData.chartData.sales
                    },
                    {
                        name: 'Profit',
                        type: chartType,
                        data: responseData.chartData.profits
                    }
                ]
            };

        case 'orderCount':
            return {
                color: ['#F56C6C'],
                legend: {
                    data: ['Order Count'],
                },
                xAxis: responseData.chartData.months,
                series: [
                    {
                        name: 'Order Count',
                        type: chartType,
                        data: responseData.chartData.orders
                    }
                ]
            };

        case 'salesVolume':
            return {
                color: ['#E6A23C'],
                legend: {
                    data: ['Sales Volume'],
                },
                xAxis: responseData.chartData.months,
                series: [
                    {
                        name: 'Sales Volume',
                        type: chartType,
                        data: responseData.chartData.volumes
                    }
                ]
            };

        case 'customerCount':
            return {
                color: ['#909399'],
                legend: {
                    data: ['Customer Count'],
                },
                xAxis: responseData.chartData.months,
                series: [
                    {
                        name: 'Customer Count',
                        type: chartType,
                        data: responseData.chartData.customers
                    }
                ]
            };

        // 产品分析相关图表
        case 'productCategorySales':
            return {
                color: ['#67C23A'],
                legend: {
                    data: ['Category Sales'],
                },
                xAxis: responseData.productShares.map(item => item.category),
                series: [
                    {
                        name: 'Category Sales',
                        type: chartType,
                        data: responseData.productShares.map(item => item.salesAmount)
                    }
                ]
            };

        case 'productUnitPriceProfit':
            return {
                color: ['#E6A23C', '#67C23A'],
                legend: {
                    data: ['Price', 'Profit'],
                },
                xAxis: responseData.categoryTrend.months,
                series: [
                    {
                        name: 'Price',
                        type: chartType,
                        data: responseData.categoryTrend.prices
                    },
                    {
                        name: 'Profit',
                        type: chartType,
                        data: responseData.categoryTrend.profits
                    }
                ]
            };

        case 'productCategorySalesVolume':
            return {
                color: ['#E6A23C'],
                legend: {
                    data: ['Sales Volume'],
                },
                xAxis: responseData.categoryTrend.months,
                series: [
                    {
                        name: 'Sales Volume',
                        type: chartType,
                        data: responseData.categoryTrend.volumes
                    }
                ]
            };

        case 'productCategorySalesDate':
            return {
                legend: {
                    data: ['Sales']
                },
                xAxis: responseData.categoryTrend.months,
                series: [
                    {
                        name: 'Sales',
                        type: chartType,
                        data: responseData.categoryTrend.sales
                    }
                ]
            };

        // 客户分析相关图表
        case 'consumptionPerCapita':
            return {
                color: ['#409EFF', '#67C23A'],
                legend: {
                    data: ['Average Consumption', 'Average Profit']
                },
                xAxis: responseData.trend.months,
                series: [
                    {
                        name: 'Average Consumption',
                        type: chartType,
                        data: responseData.trend.avgConsumption
                    },
                    {
                        name: 'Average Profit',
                        type: chartType,
                        data: responseData.trend.avgProfit
                    }
                ]
            };

        case 'customerTimePreference':
            return {
                color: ['#409EFF'],
                legend: {
                    data: ['Customer Count'],
                },
                xAxis: responseData.distribution.weekday.map(item => item.weekday),
                series: [
                    {
                        name: 'Customer Count',
                        type: chartType,
                        data: responseData.distribution.weekday.map(item => item.count)
                    }
                ]
            };

        case 'ageDistribution':
            return {
                legend: {
                    data: ['Customer Count']
                },
                xAxis: responseData.distribution.age.map(item => item.name),
                series: [
                    {
                        name: 'Customer Count',
                        type: chartType,
                        data: responseData.distribution.age.map(item => item.value)
                    }
                ]
            };

        case 'shopSalesProfit':
            return {
                color: ['#409EFF', '#67C23A'],
                legend: {
                    data: ['Sales', 'Profit']
                },
                xAxis: {
                    type: 'category',
                    data: responseData.shopTrend.months
                },
                series: [
                    {
                        name: 'Sales',
                        type: chartType,
                        data: responseData.shopTrend.sales
                    },
                    {
                        name: 'Profit',
                        type: chartType,
                        data: responseData.shopTrend.profits
                    }
                ]
            }
        case 'cumulativeSalesProfit':
            return {
                legend: {
                    data: ['Sales', 'Profit']
                },
                xAxis: responseData.chartData.months,
                series: [
                    {
                        name: 'Sales',
                        type: chartType,
                        data: responseData.chartData.monthSales
                    },
                    {
                        name: 'Profit',
                        type: chartType,
                        data: responseData.chartData.monthProfits
                    }
                ]
            }
        case 'monthlySalesProfit':
            return {
                legend: {
                    data: ['Sales', 'Profit']
                },
                xAxis: responseData.chartData.months,
                series: [
                    {
                        name: 'Sales',
                        type: chartType,
                        data: responseData.chartData.monthSales
                    },
                    {
                        name: 'Profit',
                        type: chartType,
                        data: responseData.chartData.monthProfits
                    }
                ]
            }
        case 'productCategoryDistribution':
            return {
                series: responseData.productShares.map(item => ({
                    name: item.category,
                    value: item.salesAmount,
                    percentage: item.percentage
                }))
            }
        case 'customerCityDistribution':
            return {
                series: responseData.distribution.city
            }
        case 'shopDistribution':
            return {
                series: responseData.cityData.distribution
            }

        // 默认返回示例数据
        default:
            return {
                xAxis: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
                series: [{
                    name: 'Sample Data',
                    type: chartType,
                    data: [120, 200, 150, 80, 70, 110, 130]
                }]
            };
    }
};



// 获取演示数据

const getDemoChartData = (chartType) => {

    if (['pie', 'ring', 'funnel'].includes(chartType)) {

        return {

            series: [

                { value: 1048, name: '类别A' },

                { value: 735, name: '类别B' },

                { value: 580, name: '类别C' },

                { value: 484, name: '类别D' },

                { value: 300, name: '类别E' }

            ]

        }

    } else {

        return {

            xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],

            series: [{

                name: '示例数据',

                type: chartType,

                data: [120, 200, 150, 80, 70, 110, 130]

            }]

        }

    }

}



// 渲染图表

const renderChart = (index, chartData) => {
    nextTick(() => {
        const chartDom = document.getElementById(`chart-${index}`)
        if (!chartDom) {
            console.warn(`图表DOM未找到: chart-${index}`)
            return
        }

        // 检查是否已存在实例，如果存在则销毁
        let chartInstance = echarts.getInstanceByDom(chartDom)
        if (chartInstance) {
            chartInstance.dispose()
        }

        // 创建新实例
        chartInstance = echarts.init(chartDom)

        const chart = dashboardForm.charts[index]

        // 根据图表类型处理数据格式
        let option = {}
        switch (chart.type) {
            case 'line':
            case 'bar':
            case 'area':
                option = {
                    tooltip: { trigger: 'axis' },
                    legend: chartData.legend || {},
                    color: chartData.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                    xAxis: {
                        type: 'category',
                        data: chartData.xAxis || [],
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: { type: 'value' },
                    series: chartData.series ? chartData.series.map(series => {
                        if (chart.type === 'area') {
                            return { ...series, type: 'line', areaStyle: {} }
                        }
                        return series
                    }) : []
                }
                break

            case 'pie':
            case 'ring':
                // 检查是否为特殊格式的系列配置（已经包含完整的系列配置）
                if (chartData.series && Array.isArray(chartData.series) && chartData.series[0] && chartData.series[0].type) {
                    // 直接使用提供的系列配置
                    option = {
                        tooltip: { trigger: 'item' },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            type: 'scroll',
                            show: false
                        },
                        color: chartData.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                        series: chartData.series
                    }
                } else {
                    // 常规数据数组格式
                    option = {
                        tooltip: { trigger: 'item' },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            type: 'scroll',
                            show: false
                        },
                        color: chartData.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                        series: [{
                            name: chart.title,
                            type: 'pie',
                            radius: chart.type === 'ring' ? ['40%', '70%'] : '70%',
                            data: chartData.series || [],
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    }
                }
                break

            case 'funnel':
                option = {
                    tooltip: { trigger: 'item' },
                    legend: {
                        data: (chartData.series || []).map(item => item.name),
                        type: 'scroll',
                        show: false
                    },
                    color: chartData.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                    series: [{
                        name: chart.title,
                        type: 'funnel',
                        left: '10%',
                        top: 60,
                        bottom: 60,
                        width: '80%',
                        sort: 'descending',
                        data: chartData.series || []
                    }]
                }
                break
        }

        // 设置图表配置
        chartInstance.setOption(option)

        // 保存实例引用
        chartRefs.value[index] = chartInstance
    })
}



// 使用示例数据渲染图表

const renderChartWithDemoData = (index) => {

    const chart = dashboardForm.charts[index]

    if (!chart) return



    const demoData = getDemoChartData(chart.type)

    renderChart(index, demoData)

}



// 显示添加图表对话框

const showAddChartDialog = () => {

    // 重置表单

    chartForm.title = ''

    chartForm.type = ''

    chartForm.dataSource = ''

    chartForm.options = ''

    chartDialogVisible.value = true

}



// 删除当前图表

const deleteChart = () => {

    chartDialogVisible.value = false

}



// 添加图表

const addChart = () => {

    if (!chartForm.dataSource || !chartForm.type) {

        ElMessage.error('Please select the data type and chart type')

        return

    }



    // 仅使用数据源的标签作为标题

    const dataSourceLabel = chartOptions.value.dataSources.find(item => item.value === chartForm.dataSource)?.label || ''

    const title = dataSourceLabel



    // 创建一个JSON对象作为数据源配置

    const dataSourceConfig = {

        type: chartForm.dataSource,

        options: {}

    }



    // 将数据源配置转换为JSON字符串

    const chart = {

        title: title,

        type: chartForm.type,

        dataSource: JSON.stringify(dataSourceConfig),

        options: '{}',

        displayOrder: dashboardForm.charts.length

    }



    dashboardForm.charts.push(chart)

    chartDialogVisible.value = false



    // 重置表单

    chartForm.dataSource = ''

    chartForm.type = ''



    // 提示成功

    ElMessage.success('Chart added successfully')




    nextTick(() => {

        // 获取刚添加的图表索引

        const newChartIndex = dashboardForm.charts.length - 1

        // 加载该图表的数据

        loadChartData(newChartIndex)

    })

}



// 定义一个加载所有图表的函数

const loadAllCharts = () => {

    dashboardForm.charts.forEach((chart, index) => {

        loadChartData(index)

    })

}



// 从仪表板中移除特定位置的图表

const removeChartAt = (index) => {

    ElMessageBox.confirm('确定要删除此图表吗？', '提示', {

        confirmButtonText: '确定',

        cancelButtonText: '取消',

        type: 'warning'

    }).then(() => {

        // 先销毁图表实例

        const chartDom = document.getElementById(`chart-${index}`)

        if (chartDom) {

            const instance = echarts.getInstanceByDom(chartDom)

            if (instance) {

                instance.dispose()

            }

        }



        // 然后移除图表数据

        dashboardForm.charts.splice(index, 1)

        ElMessage.success('Chart deleted successfully')



        // 更新引用数组

        chartRefs.value.splice(index, 1)



        // 重新渲染其余图表

        nextTick(() => {

            loadAllCharts()

        })

    }).catch(() => { })

}

// 随机生成四位纯数字的仪表盘type
const generateDashboardType = () => {
    const type = Math.floor(Math.random() * 9000) + 1000
    return type
}

const loadingStatus = ref(false)
// 保存仪表板
const saveDashboard = async () => {
    try {
        loadingStatus.value = true
        dashboardForm.type = generateDashboardType().toString()

        const res = await createDashboard(dashboardForm)
        console.log('Dashboard creation result:', res)

        ElMessage.success('Dashboard created successfully')

        // 根据返回格式获取正确的ID
        const dashboardId = typeof res === 'object' ? res.id : res

        // 使用正确的ID进行跳转
        router.push(`/analysis/${dashboardId}`)

    } catch (error) {
        ElMessage.error('Failed to create dashboard: ' + error.message)
    } finally {
        loadingStatus.value = false
    }
}



// 取消创建

const cancelCreate = () => {

    ElMessageBox.confirm('Unsaved content will be lost', 'Tips', {

        confirmButtonText: 'Confirm',

        cancelButtonText: 'Cancel',

        type: 'warning'

    })

        .then(() => {

            router.go(-1)

        })

        .catch(() => { })

}



// 监听图表数组变化，更新引用

watch(() => dashboardForm.charts.length, () => {

    nextTick(() => {

        loadAllCharts()

    })

})



// 组件卸载时清理所有图表实例

onUnmounted(() => {

    chartRefs.value.forEach(instance => {

        if (instance) {

            instance.dispose()

        }

    })

})



onMounted(() => {

    // 检查用户角色

    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

    if (userInfo.role !== 'ADMIN') {

        ElMessage.error('Only admins can create dashboards')

        router.push('/analysis/core')

    }

})

</script>



<style scoped>
.create-dashboard-container {

    width: calc(100vw - 200px);

    padding: 20px;

    margin: 0 auto;

}



.dashboard-form-section {

    background-color: #fff;

    border-radius: 4px;

    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

    padding-bottom: 20px;

}



.form-header {

    padding: 20px;

}



.form-group {

    display: flex;

    align-items: center;

    margin-bottom: 15px;

}



.form-group label {

    margin-right: 10px;

    font-weight: bold;

}



.form-actions {

    display: flex;

    justify-content: flex-end;

    margin-top: 20px;

    gap: 10px;

}



.cancel-btn {

    background-color: #ccc;

    color: #fff;

    border: none;

}



.save-btn {

    background-color: #409EFF;

    color: #fff;

    border: none;

}



/* 图表区域样式 */

.charts-container {

    padding: 0 20px 20px;

}



.chart-card {

    margin-bottom: 20px;

    border-radius: 8px;

    height: 380px;

}



.chart-title {

    display: flex;

    justify-content: space-between;

    align-items: center;

    padding-bottom: 10px;

    border-bottom: 1px solid #eee;

    margin-bottom: 10px;

    font-size: 16px;

    font-weight: 500;

    color: #303133;

}



.delete-chart-btn {

    font-size: 12px;

}



.chart-container {

    height: 320px;

    width: 100%;

}



/* 添加图表卡片 */

.chart-add-card {

    height: 380px;

    background-color: #f5f5f5;

    border-radius: 8px;

    display: flex;

    justify-content: center;

    align-items: center;

    cursor: pointer;

    margin-bottom: 20px;

    transition: background-color 0.3s;

}



.chart-add-card:hover {

    background-color: #e9e9e9;

}



.chart-add-placeholder {

    text-align: center;

    color: #999;

}



.add-icon {

    font-size: 24px;

    margin-bottom: 10px;

}



.chart-dialog {

    border-radius: 10px;

    overflow: hidden;

}



.chart-dialog-content {

    padding: 10px;

}



.chart-select {

    width: 100%;

    margin-bottom: 15px;

}



.dialog-footer {

    display: flex;

    justify-content: space-between;

    margin-top: 20px;

}



.delete-btn {

    background-color: #F56C6C;

    color: #fff;

    border: none;

}



.confirm-btn {

    background-color: #409EFF;

    color: #fff;

    border: none;

}
</style>